package lagou.homework.lagou_homework_rocketmq.consumer;

import lagou.homework.lagou_homework_rocketmq.entity.Order;
import lagou.homework.lagou_homework_rocketmq.entity.Seckill;
import lagou.homework.lagou_homework_rocketmq.entity.SeckillVo;
import lagou.homework.lagou_homework_rocketmq.entity.TimeoutOrderMessage;
import lagou.homework.lagou_homework_rocketmq.repository.GoodsRepository;
import lagou.homework.lagou_homework_rocketmq.repository.OrderRepository;
import lagou.homework.lagou_homework_rocketmq.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@RocketMQMessageListener(topic = "order_timeout", consumerGroup = "order_timeout_consumer")
public class OrderTimeoutConsumer implements RocketMQListener<TimeoutOrderMessage> {
    @Autowired
    private OrderRepository orderRepository;
    @Autowired
    private GoodsRepository goodsRepository;
    @Autowired
    private OrderService orderService;

    @Override
    public void onMessage(TimeoutOrderMessage timeoutOrderMessage) {
        Order order = orderRepository.findByOrderNo(timeoutOrderMessage.getOrder().getOrderNo());
        String seckillId = timeoutOrderMessage.getSeckillId();
        if(order == null){
            return;
        }
        /**
         * 检查订单状态是否是已支付
         */
        if(order.getStatus() == 0){
            log.info("监听到超时未支付订单:{}",timeoutOrderMessage.getOrder().getOrderNo());
            order.setStatus(2);
            orderService.rollback(order,seckillId);
        }
    }
}
